using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MusicLibrary.Server.Models;
using MusicLibrary.Server.Data;
using System.Linq;

// [Authorize] // 临时注释掉认证要求
[ApiController]
[Route("api/music")]
public class MusicController : ControllerBase
{
    private readonly MusicLibraryContext _context;
    public MusicController(MusicLibraryContext context) => _context = context;

    [HttpGet]
    public async Task<IActionResult> GetSongs([FromQuery] string search = "", [FromQuery] string type = "all")
    {
        var query = _context.Songs.AsQueryable();

        if (!string.IsNullOrWhiteSpace(search))
        {
            search = search.ToLower();
            query = query.Where(s => 
                s.Title.ToLower().Contains(search) || 
                s.Artist.ToLower().Contains(search) ||
                s.Genre.ToLower().Contains(search));
        }

        if (type != "all")
        {
            switch (type)
            {
                case "songs":
                    query = query.Where(s => s.Status == "active");
                    break;
                case "albums":
                    query = query.Where(s => s.Status == "album");
                    break;
                case "artists":
                    query = query.Where(s => s.Status == "artist");
                    break;
            }
        }

        var songs = await query.ToListAsync();
        return Ok(new { code = 0, data = songs });
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetSong(int id)
    {
        var song = await _context.Songs.FindAsync(id);
        if (song == null)
        {
            return NotFound(new { code = 1, message = "歌曲不存在" });
        }
        return Ok(new { code = 0, data = song });
    }

    [HttpGet("trending")]
    public async Task<IActionResult> GetTrendingSongs()
    {
        var songs = await _context.Songs
            .OrderByDescending(s => s.UploadDate)
            .Take(10)
            .ToListAsync();
        return Ok(new { code = 0, data = songs });
    }

    [HttpGet("covers")]
    public IActionResult GetCovers()
    {
        var covers = new[]
        {
            "/music_covers/cover1.jpg",
            "/music_covers/cover2.jpg",
            "/music_covers/cover3.jpg",
            "/music_covers/cover4.jpg",
            "/music_covers/cover5.jpg",
            "/music_covers/cover6.jpg"
        };
        return Ok(new { code = 0, data = covers });
    }
}